<template>
  <view class="container">
    <!-- Tab Bar -->
    <view class="tab-bar-container">
      <uni-segmented-control
        :current="currentTab"
        :values="['设备列表', '设备配网']"
        @clickItem="onClickTab"
        styleType="text"
        activeColor="#007aff"
      ></uni-segmented-control>
    </view>

    <!-- 内容区域 -->
    <view class="content-area">
      <!-- 蓝牙设备列表 Tab -->
      <view v-if="currentTab === 0" class="device-list-content">
        <scroll-view scroll-y class="device-scroll-view">
          <view
            v-for="device in deviceList"
            :key="device.id"
            class="device-item"
            @click="bindViewConnect(device.deviceId)"
          >
			<view class="device-icon-wrapper">
			  <image :src="device.image || '/static/default-device-icon.png'" class="device-actual-image"></image>
			</view>           
			 <view class="device-info">
              <text class="device-name">{{ device.name || '未知设备' }}</text>
            </view>
          </view>
          <view v-if="deviceList.length === 0" class="empty-list">
            <text>暂未扫描到设备</text>
          </view>
        </scroll-view>
      </view>

      <!-- 设备配网 Tab -->
      <view v-if="currentTab === 1" class="network-config-content">
        <!-- 选中的设备信息 (这里的样式您可以选择是否与列表项统一) -->
        <view v-if="selectedDevice" class="selected-device-display"> <!-- 使用新的类名以区分 -->
          <image :src="selectedDevice.image || '/static/default-device-icon.png'" class="device-icon"></image>
          <view class="device-info">
            <text class="device-name">{{ selectedDevice.name || '未知设备' }}</text>
          </view>
        </view>
        <!-- 配网表单 -->
        <view class="form">
			<text>WiFi名称</text>
          <view class="form-item">
            <input v-model="ssid" placeholder="请输入WiFi名称" maxlength="32" />
          </view>
		   <text>WiFi密码</text>
          <view class="form-item">
            <input v-model="password" type="password" placeholder="请输入WiFi密码" maxlength="64" />
          </view>
          <button class="submit-btn" @click="startConfig">开始配网</button>
        </view>
      </view>
    </view>

    <!-- Loading 弹窗 -->
    <uni-popup ref="loadingPopup" type="center" :mask-click="false" mask-background-color="rgba(0,0,0,0)">
      <view class="loading-box">
        <view class="loading-spinner"></view>
		<text class="text-overlay">{{ loadingMessage }}</text>
      </view>
    </uni-popup>
	
  </view>
  
</template>


<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import md5 from 'md5';
import { filterDevice, writeData, getFrameCTRLValue, isSubcontractor ,fetchBLEMTU, actualMtu, SUBTYPE_CUSTOM_DATA} from '@/utils/blufi';
import { bindByDeviceId } from '../../app/device';
// 定义蓝牙设备类型
interface BluetoothDevice {
  id: string;
  deviceId: string;
  name: string;
  RSSI: number;
  image?: string;
  [key: string]: any;
}

// 页面状态
const currentTab = ref<number>(0);
const deviceList = reactive<BluetoothDevice[]>([]);
const isDiscovering = ref<boolean>(false);
const loadingPopup = ref<any>(null);
const loadingMessage = ref('');

const ssid = ref<string>('');
const password = ref<string>('');
const sequence = ref<number>(0);
const md5Key = ref<number[]>([]);

// 连接状态
const deviceId = ref<string>('');
const serviceId = ref<string>('');
const writeCharId = ref<string>('');
const readCharId = ref<string>('');
const customId = ref('');
const selectedDevice = ref<BluetoothDevice | null>(null);

// 全局配置
const SERVICE_UUID = '0000FFFF-0000-1000-8000-00805F9B34FB';
const CHARACTERISTIC_WRITE_UUID = '0000FF01-0000-1000-8000-00805F9B34FB';
const CHARACTERISTIC_READ_UUID = '0000FF02-0000-1000-8000-00805F9B34FB';
const PACKAGE_VALUE = 0x01;
const PACKAGE_CONTROL_VALUE = 0x00;
const SUBTYPE_NEG = 0x00;
const SUBTYPE_WIFI_MODEl = 0x02;
const SUBTYPE_SET_SSID = 0x02;
const SUBTYPE_SET_PWD = 0x03;
const SUBTYPE_END = 0x03;
const SUBTYPE_SET_SEC_MODE = 0x01;
const DIRECTION_OUTPUT = 0;

// 手动 UTF-8 编码函数
const encodeUTF8 = (str: string): number[] => {
  const bytes: number[] = [];
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i);
    if (charCode < 0x80) {
      bytes.push(charCode);
    } else if (charCode < 0x800) {
      bytes.push(0xc0 | (charCode >> 6), 0x80 | (charCode & 0x3f));
    } else if (charCode < 0x10000) {
      bytes.push(0xe0 | (charCode >> 12), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    } else {
      bytes.push(0xf0 | (charCode >> 18), 0x80 | ((charCode >> 12) & 0x3f), 0x80 | ((charCode >> 6) & 0x3f), 0x80 | (charCode & 0x3f));
    }
  }
  return bytes;
};

const onClickTab = (e: { currentIndex: number }) => {
console.log('[onClickTab] Start. Index:', e.currentIndex, 'Current deviceId:', deviceId.value, 'selectedDevice:', selectedDevice.value);

  if (e.currentIndex === 1 && !deviceId.value) {
    uni.showToast({ title: '请先选择设备', icon: 'none' });
    return;
  }

  if (e.currentIndex === 0) {
    // 断开当前蓝牙连接
    if (deviceId.value) {
      uni.closeBLEConnection({
        deviceId: deviceId.value,
        success: () => {
          console.log('断开设备:', deviceId.value);
        },
        fail: (err) => {
          console.error('断开连接失败:', JSON.stringify(err, null, 2));
        },
      });
    }

    // 清空连接状态和选中的设备
    deviceId.value = '';
    serviceId.value = '';
    writeCharId.value = '';
    readCharId.value = '';
    selectedDevice.value = null;

    // 重新扫描蓝牙设备
    loadingMessage.value = '设备扫描中...';
	loadingPopup.value?.open();
    getBluDevice();
  }

  currentTab.value = e.currentIndex;
};

// 初始化蓝牙并获取设备
const getBluDevice = async () => {
  try {
    // 确保蓝牙适配器已初始化
    await initializeBluetooth();
    const state = await checkBluetoothState();
    if (!state.available) {
      showBluetoothPrompt();
      return;
    }

    // 如果正在扫描，先停止
    if (state.discovering || isDiscovering.value) {
     uni.stopBluetoothDevicesDiscovery({
        success: () => {
          console.log('停止现有设备扫描');
          isDiscovering.value = false;
        },
        fail: (err) => {
          console.error('停止扫描失败:', JSON.stringify(err, null, 2));
        },
      });
    }

    // 清空现有设备列表
    deviceList.splice(0, deviceList.length);
    console.log('清空设备列表，准备重新扫描');

    // 开始新的扫描
    await startDeviceDiscovery();
    fetchBluetoothDevices();
  } catch (err) {
    console.error('初始化蓝牙失败:', JSON.stringify(err, null, 2));
    showBluetoothPrompt();
	loadingPopup.value?.close();
  }
};

// 初始化蓝牙适配器
const initializeBluetooth = () => {
  return new Promise<void>((resolve, reject) => {
    uni.openBluetoothAdapter({
      success: () => {
        console.log('蓝牙适配器初始化成功');
        resolve();
      },
      fail: (err) => {
        console.error('蓝牙初始化失败:', JSON.stringify(err, null, 2));
        reject(err);
      },
    });
  });
};

// 检查蓝牙适配器状态
const checkBluetoothState = () => {
  return new Promise<{ available: boolean; discovering: boolean }>((resolve, reject) => {
    uni.getBluetoothAdapterState({
      success: (res) => {
        console.log('蓝牙适配器状态:', res);
        resolve(res);
      },
      fail: (err) => {
        console.error('获取蓝牙状态失败:', JSON.stringify(err, null, 2));
        reject(err);
      },
    });
  });
};

// 启动设备扫描
const startDeviceDiscovery = () => {
  return new Promise<void>((resolve, reject) => {
    uni.startBluetoothDevicesDiscovery({
      success: () => {
        console.log('开始扫描蓝牙设备');
        isDiscovering.value = true;
        resolve();
      },
      fail: (err) => {
        console.error('启动扫描失败:', JSON.stringify(err, null, 2));
        if (err.errMsg.includes('already discovering')) {
          console.log('已在扫描中，忽略错误');
          isDiscovering.value = true;
          resolve();
        } else {
          reject(err);
        }
      },
    });
  });
};

// 获取蓝牙设备（去重）
const fetchBluetoothDevices = () => {
  const knownDeviceIds = new Set<string>();

  uni.getBluetoothDevices({
    success: (res) => {
      console.log('获取设备成功:', res.devices);
      const filteredDevices = filterDevice(res.devices, 'name').map((device) => ({
        ...device,
        id: device.deviceId,
      }));
		console.log("蓝牙设备："+filteredDevices);
      const uniqueDevices = filteredDevices.filter((device) => {
        if (knownDeviceIds.has(device.deviceId)) {
          return false;
        }
        knownDeviceIds.add(device.deviceId);
        return true;
      });

      if (uniqueDevices.length > 0) {
        console.log('更新设备列表:', uniqueDevices);
        deviceList.splice(0, deviceList.length, ...uniqueDevices);
      }
	  //delay(30000)
	  //loadingPopup.value?.close();
	  setTimeout(() => {
	    // 提交成功后清空表单并返回上一页
	    loadingPopup.value?.close();
	  }, 500);
    },
    fail: (err) => {
      console.error('获取设备失败:', JSON.stringify(err, null, 2));
      uni.showToast({ title: '获取设备失败', icon: 'none' });
	  loadingPopup.value?.close();
    },
  });

  uni.onBluetoothDeviceFound((res) => {
    const filteredDevices = filterDevice(res.devices, 'name').map((device) => ({
      ...device,
      id: device.deviceId,
    }));

    const uniqueDevices = filteredDevices.filter((device) => {
      if (knownDeviceIds.has(device.deviceId)) {
        return false;
      }
      knownDeviceIds.add(device.deviceId);
      return true;
    });

    if (uniqueDevices.length > 0) {
      console.log('追加新设备:', uniqueDevices);
      deviceList.push(...uniqueDevices);
    }
  });

  // 超时关闭加载提示
  setTimeout(() => {
    if (deviceList.length === 0) {
      uni.hideLoading();
      //uni.showToast({ title: '未发现设备，请重试', icon: 'none' });
    } else {
      uni.hideLoading();
    }
  }, 3000);
};

// 显示蓝牙未开启提示
const showBluetoothPrompt = () => {
  uni.showModal({
    title: '蓝牙未开启',
    content: '请在手机设置中开启蓝牙并授权小程序使用蓝牙功能',
    confirmText: '重试',
    cancelText: '取消',
    success: (res) => {
      if (res.confirm) {
        getBluDevice();
      }
    },
  });
};

// 点击设备，发起连接并切换Tab
const bindViewConnect = async (id: string) => {
  deviceId.value = id;
  // 设置动态连接文案
  loadingMessage.value = '正在连接蓝豆包AI玩具';
  loadingPopup.value?.open();
  try {
    await uni.createBLEConnection({ deviceId: id, timeout: 10000 });
    console.log('蓝牙连接成功:', id);
    const services = await uni.getBLEDeviceServices({ deviceId: id });
    const service = services.services.find((s) => s.uuid.toUpperCase() === SERVICE_UUID);
    if (!service) throw new Error('未找到指定服务');
    serviceId.value = service.uuid;

    const characteristics = await uni.getBLEDeviceCharacteristics({
      deviceId: id,
      serviceId: service.uuid,
    });
    console.log('所有特征值:', characteristics.characteristics);
    const writeChar = characteristics.characteristics.find(
      (c) => c.uuid.toUpperCase() === CHARACTERISTIC_WRITE_UUID
    );
    const readChar = characteristics.characteristics.find(
      (c) => c.uuid.toUpperCase() === CHARACTERISTIC_READ_UUID
    );
    console.log('特征值属性:', readChar?.properties);
    if (!writeChar || !readChar) throw new Error('未找到指定特征值');
    writeCharId.value = writeChar.uuid;
    readCharId.value = readChar.uuid;

    selectedDevice.value = deviceList.find((device) => device.deviceId === id) || null;
    currentTab.value = 1;
	delay(5000)
    loadingPopup.value?.close();

    // 移除旧监听器
    uni.offBLECharacteristicValueChange();

    // 初始化序列号
    sequence.value = 0;

    // 获取MTU
    await fetchBLEMTU(deviceId.value);
    console.log(`将使用MTU: ${actualMtu.value} 字节`);

    // 启用通知并发送自定义ID请求
    await new Promise<void>((resolve, reject) => {
      uni.notifyBLECharacteristicValueChange({
        deviceId: id,
        serviceId: service.uuid,
        characteristicId: readCharId.value,
        state: true,
        success: async () => {
          console.log('启用通知成功');

            // 注册全局监听器
			// 用于存储分包数据的缓冲区
			let packetBuffer = [];
			let expectedSequence = 0;
			
			
uni.onBLECharacteristicValueChange((res) => {
  const value = new Uint8Array(res.value);
  const type = value[0] & 0x03;
  const subType = (value[0] >> 2) & 0x3F;
  const sequenceNum = value[2];

  console.log('收到分包:', {
    sequenceNum,
    currentLength: packetBuffer.length,
    data: Array.from(value.slice(6)).map(b => b.toString(16).padStart(2, '0')),
    buffer: packetBuffer.map(b => b.toString(16).padStart(2, '0')),
  });
  console.log('收到蓝牙通知:', JSON.stringify({
    type,
    subType,
    sequenceNum,
    value: Array.from(value),
    rawValue: Array.from(value).map(b => b.toString(16).padStart(2, '0'))
  }, null, 2));

  if (type === PACKAGE_VALUE && subType === SUBTYPE_CUSTOM_DATA) {
    // 检查序列号，确保按顺序处理
    if (sequenceNum === expectedSequence) {
      // 提取数据部分，针对第一包跳过帧头（ff a1），最后一包从 value[4] 开始
	  let dataStartIndex = 6;
	  if(sequenceNum === 0){
		  if(actualMtu.value>23){
		  	  dataStartIndex = 6;
		  }else{
			  dataStartIndex = 8;
		  }
	  }else  {
		  if(actualMtu.value>23){
			  dataStartIndex=0;
		  }else{
			  if (value.length <= 6 && value.length > 4){
					  // 最后一包可能长度较短，从 value[4] 开始提取
					  dataStartIndex = 4;
			  }
		  }
      }
	
	  
      const data = Array.from(value.slice(dataStartIndex));
      packetBuffer.push(...data);

      expectedSequence++;
      // 检查是否收集到完整的 UUID（36 字节）
      if (packetBuffer.length >= 36) {
        const idData = packetBuffer.slice(0, 36);
        console.log('原始ID数据:', idData, '十六进制:', idData.map(b => b.toString(16).padStart(2, '0')));
        customId.value = String.fromCharCode(...idData);
        console.log(`收到设备自定义ID: ${customId.value}`);

        // 重置缓冲区和序列号
        packetBuffer = packetBuffer.slice(36);
        expectedSequence = sequenceNum + 1;
      }
    } else {
      console.warn(`序列号不匹配: 期望 ${expectedSequence}, 收到 ${sequenceNum}`);
      packetBuffer = [];
      expectedSequence = sequenceNum;
    }
  } else {
    console.warn(`未识别的通知: type=${type}, subType=${subType}, value=`, Array.from(value));
  }
});

          // 发送自定义ID请求
          await sendCustomData();
          console.log('已发送自定义ID请求');
          resolve();
        },
        fail: (err) => {
          console.error('启用通知失败:', err);
          reject(new Error('启用通知失败'));
        },
      });
    });

    uni.onBLEConnectionStateChange((res) => {
      console.log('连接状态变化:', res);
      if (!res.connected) {
        console.error('设备已断开:', res.deviceId);
        customId.value = ''; // 清空ID
      }
    });
  } catch (err) {
    console.error('连接失败:', JSON.stringify(err, null, 2));
    loadingPopup.value?.close();
	loadingMessage.value = '连接设备失败';
	loadingPopup.value?.open();
  }
};

// 写入蓝牙数据
const writeBLEData = async (data: number[]) => {
  try {
    return await new Promise<void>((resolve, reject) => {
      uni.writeBLECharacteristicValue({
        deviceId: deviceId.value,
        serviceId: serviceId.value,
        characteristicId: writeCharId.value,
        value: new Uint8Array(data).buffer,
        success: () => {
          console.log('写入数据:', data);
          resolve();
        },
        fail: (err) => {
          console.error('写入失败:', JSON.stringify(err, null, 2));
          reject(new Error(`写入失败: ${JSON.stringify(err)}`));
        },
      });
    });
  } catch (err) {
    console.error('writeBLEData 错误:', JSON.stringify(err, null, 2));
    throw err;
  }
};

// 延迟函数
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));

// DH 协商（已禁用）
const performDHNegotiation = async () => {
  console.log('DH 协商已禁用，跳过密钥协商步骤');
  md5Key.value = [];
};

// 等待固件公钥（禁用 DH 时不需要）
const waitForServerKey = () => {
  return new Promise<number[]>((resolve) => {
    console.log('DH 协商已禁用，无需等待固件公钥');
    resolve([]);
  });
};

const sendDataWithSubcontract = async (data: number[], type: number, subType: number) => {
  let remainingData = data;
  let packetCount = 0;
  while (remainingData.length > 0) {
    const packet = writeData(
      type,
      subType,
      getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, remainingData.length > (actualMtu.value - 3)),
      sequence.value,
      remainingData.length,
      remainingData
    );
    const sub = isSubcontractor(packet, false, sequence.value, false);
    console.log(`分包${++packetCount} (seq=${sequence.value}, len=${sub.len}, flag=${sub.flag}, mtu=${actualMtu.value}):`, sub.lenData);
    await writeBLEData(sub.lenData);
    sequence.value++;
    await delay(10);
    if (sub.flag) {
      console.log(`剩余数据:`, sub.laveData);
      remainingData = sub.laveData;
    } else {
      remainingData = [];
    }
  }
};

const sendCustomData = async (data: number[] = [0xFF, 0xA1]) => {
  let remainingData = data;
  let packetCount = 0;
  while (remainingData.length > 0) {
    const packet = writeData(
      PACKAGE_VALUE,
      SUBTYPE_CUSTOM_DATA,
      getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, remainingData.length > (actualMtu.value - 3)),
      sequence.value,
      remainingData.length,
      remainingData
    );
    const sub = isSubcontractor(packet, false, sequence.value, false);
    console.log(
      `发送自定义数据 - 分包${++packetCount} (seq=${sequence.value}, len=${sub.len}, flag=${sub.flag}, mtu=${actualMtu.value}):`,
      sub.lenData
    );
    await writeBLEData(sub.lenData);
    sequence.value++;
    // await delay(10);
    if (sub.flag) {
      console.log(`剩余数据:`, sub.laveData);
      remainingData = sub.laveData;
    } else {
      remainingData = [];
    }
  }
};

// 开始配网
const startConfig = async () => {
  console.log('开始配网，设备ID:', deviceId.value, 'SSID:', ssid.value, '密码:', password.value, '自定义ID:', customId.value);
  try {
    if (!deviceId.value) throw new Error('请先选择设备');
    if (!ssid.value.trim() || !password.value.trim()) throw new Error('请输入WiFi名称和密码');
    if (!customId.value) throw new Error('未获取到设备ID');
	
	loadingMessage.value = '正在配网';
	loadingPopup.value?.open();
    sequence.value = 1; // 从seq=1开始

    // 获取MTU
    await fetchBLEMTU(deviceId.value);
    console.log(`将使用MTU: ${actualMtu.value} 字节`);

    // 启用通知
    await new Promise<void>((resolve, reject) => {
      uni.notifyBLECharacteristicValueChange({
        deviceId: deviceId.value,
        serviceId: serviceId.value,
        characteristicId: readCharId.value,
        state: true,
        success: () => {
          console.log('启用通知成功');
          resolve();
        },
        fail: (err) => {
          console.error('启用通知失败:', err);
          reject(new Error('启用通知失败'));
        },
      });
    });

    // 发送安全模式
    const secModeData = [0x00]; // 无加密
    await sendDataWithSubcontract(secModeData, PACKAGE_CONTROL_VALUE, SUBTYPE_SET_SEC_MODE);
    console.log('已发送安全模式');

    // 发送WiFi模式
    const opModeData = [0x01];
    await sendDataWithSubcontract(opModeData, PACKAGE_CONTROL_VALUE, SUBTYPE_WIFI_MODEl);

    // 发送SSID
    const ssidData = encodeUTF8(ssid.value.trim());
    console.log('SSID Data:', ssidData);
    await sendDataWithSubcontract(ssidData, PACKAGE_VALUE, SUBTYPE_SET_SSID);

    // 发送密码
    const pwdData = encodeUTF8(password.value.trim());
    console.log('Password Data:', pwdData);
    await sendDataWithSubcontract(pwdData, PACKAGE_VALUE, SUBTYPE_SET_PWD);

    // 发送结束标志
    const endPacket = writeData(
      PACKAGE_CONTROL_VALUE,
      SUBTYPE_END,
      getFrameCTRLValue(false, false, DIRECTION_OUTPUT, false, false),
      sequence.value++,
      0,
      []
    );
    console.log('发送结束标志:', endPacket);
    await writeBLEData(endPacket);

    await waitForConfigResult();
  } catch (err: any) {
    console.error('配网失败:', err);
    uni.hideLoading();
    uni.showToast({ title: err.message || '配网失败', icon: 'none', duration: 2000 });
  }
};

// 监听配网结果
const waitForConfigResult = () => {
  return new Promise<void>((resolve, reject) => {
    let lastSequence = sequence.value - 1;
    const handler = (res: any) => {
      const value = new Uint8Array(res.value);
      const type = value[0] & 0x03;
      const subType = (value[0] >> 2) & 0x3F;
      const sequenceNum = value[2];
      console.log('收到配网结果通知:', {
        type,
        subType,
        sequenceNum,
        value: Array.from(value)
      });
      lastSequence = sequenceNum;

      if (type === PACKAGE_VALUE && subType === 15) {
        uni.hideLoading();
        uni.offBLECharacteristicValueChange(handler);
		
		// 设置动态连接文案
		loadingMessage.value = '配网成功';
		loadingPopup.value?.open();
	 delay(1500);;
		loadingPopup.value?.close();
        resolve();
		// 绑定设备
		const bindRes = bindByDeviceId(customId.value);
		console.log(bindRes);
		currentTab.value = 0;
		ssid.value = '';
		password.value = '';
		deviceId.value = '';
		customId.value = '';
		serviceId.value = '';
		writeCharId.value = '';
		readCharId.value = '';
		selectedDevice.value = null;
		delay(1500);
	
		// 跳转到完善信息
		uni.navigateTo({
		  url: `/pages/complateProfile/complateProfile`,
		});
		
      } else if (type === PACKAGE_VALUE && subType === 18) {
        console.error('配网失败，固件错误代码:', Array.from(value.slice(4)));
        uni.offBLECharacteristicValueChange(handler);
        loadingMessage.value = '配网失败';
        loadingPopup.value?.open();
        delay(3000);
        loadingPopup.value?.close();
      } else {
        console.warn(`未识别的通知: type=${type}, subType=${subType}, value=`, Array.from(value));
      }
    };
    uni.onBLECharacteristicValueChange(handler);
    setTimeout(() => {
      uni.offBLECharacteristicValueChange(handler);
	  // 设置动态连接文案
	  loadingMessage.value = '配网失败';
	  loadingPopup.value?.open();
	  delay(3000);
	  loadingPopup.value?.close();
    }, 5000);
  });
};

const checkLocationServiceEnabled= () => {
	const isAndroid = uni.getSystemInfoSync().platform === 'android';
	if (isAndroid) {
	  wx.getLocation({
		type: 'wgs84',
		success: () => {
		  console.log('系统定位已开启');
		},
		fail: (err) => {
		  console.log('可能系统定位未开启', err);
		  uni.showModal({
			title: '系统定位未开启',
			content: '请前往系统设置打开定位服务，否则无法搜索蓝牙设备',
		  });
		}
	  });
	}
}


// 页面加载
onMounted(() => {
 checkLocationServiceEnabled();
 loadingMessage.value = '设备扫描中...';
 loadingPopup.value?.open();
 getBluDevice();
});

// 页面卸载
onUnmounted(() => {
  if (isDiscovering.value) {
    uni.stopBluetoothDevicesDiscovery({
      success: () => {
        console.log('停止设备扫描');
        isDiscovering.value = false;
      },
    });
  }
  if (deviceId.value) {
    uni.closeBLEConnection({
      deviceId: deviceId.value,
      success: () => {
        console.log('断开设备:', deviceId.value);
      },
    });
  }
  uni.offBluetoothDeviceFound();
  uni.offBLECharacteristicValueChange();
});
</script>

<style scoped>
.container {
  /* 页面整体内边距，如果列表容器占满宽度，这里的左右边距可以考虑去掉或减小 */
  padding: 20rpx 0; /* 上下保留，左右由内部元素控制 */
  background: #f5f5f5; /* UI截图显示列表外的背景色偏灰 */
  min-height: 100vh;
  box-sizing: border-box;
}

/* 这个自定义头部在您的模板中似乎没有用到，如果确实不用可以移除 */
.custom-header {
  padding: 20rpx 30rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header-title {
  font-family: Source Han Sans, Source Han Sans;
  font-weight: 300;
  font-size: 36rpx;
  color: #333;
}
/* Tab栏容器样式 */
.tab-bar-container {
  padding: 20rpx 30rpx;
  background: #fff; /* Tab栏背景白色 */
  border-bottom: 1rpx solid #f0f0f0; /* Tab栏和内容区之间的细微分割 */
}

/* 内容区域容器 */
.content-area {
  /* padding: 20rpx 30rpx; */ /* 移除这里的内边距，让 device-list-content 自己控制 */
  background: #f5f5f5; /* 内容区背景，与container一致 */
}

.device-list-content {
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.device-scroll-view {
  max-height: calc(100vh - 400rpx); /* 可根据实际Tab栏和可能的底部导航高度调整 */
}


.device-item {
  display: flex;
  align-items: center; /* 保持：确保图标和设备信息块垂直居中 */
  padding: 20rpx;
  border-bottom: 2rpx solid #eee;
}

.selected-device {
  display: flex;
  align-items: center; /* 保持：确保图标和设备信息块垂直居中 */
  background: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
}

.device-icon {
  width: 100rpx;
  height: 100rpx;
  min-width: 100rpx;
  min-height: 100rpx;
  object-fit: cover;
  margin-right: 20rpx;
  background-color: #f0f0f0; /* 新增：浅灰色背景 (可以根据喜好调整颜色，例如 #e9e9e9, #f5f5f5 等) */
  /* 如果希望背景也有圆角，可以加上，比如和你的图片圆角一致 */
  /* border-radius: 10rpx; */ /* 示例圆角，根据你的图片调整 */
}

.device-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 修改：使其子项（设备名称、ID）水平靠左 */
  justify-content: center;  /* 新增：如果device-info块本身有高度，则其内部文本垂直居中 */
}

.device-name {
  font-size: 32rpx;
  color: #000;
  /* margin-bottom: 10rpx; */ /* 如果只有设备名称，可以考虑移除或减小这个，使单行文本更居中。如果还有device-id，则保留它来分隔 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left; /* 确保文本本身是左对齐的，配合 align-items: flex-start */
}

.device-id {
  font-size: 24rpx;
  color: #888;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left; /* 确保文本本身是左对齐的 */
}

/* 列表为空时的提示样式 */
.empty-list {
  padding: 60rpx 40rpx; /* 上下多一些内边距 */
  text-align: center;
  color: #999;
  font-size: 28rpx;
  background-color: #fff; /* 确保在列表容器内背景一致 */
}

/* 设备配网Tab内容区域 */
.network-config-content {
  display: flex;
  flex-direction: column;
  gap: 20rpx; /* 项目之间的间距 */
  /* padding: 30rpx; */ /* 配网内容区的内边距 */
}


/* 配网表单样式 */
.form {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}

.form-item text { /* WiFi名称/密码的标签文本 */
  width: 150rpx;
  font-size: 30rpx; /* 稍微调整标签字号 */
  color: #333;
  margin-right: 10rpx; /* 标签和输入框间 sedikit 间距 */
}

.form-item input {
  flex: 1;
  font-size: 28rpx;
  /* width: 690rpx; */ /* 使用flex:1后，width可以不用写死 */
  height: 90rpx; /*  调整输入框高度 */
  background: #F4F4F4;
  border-radius: 15rpx; /* 调整输入框圆角 */
  padding: 0 20rpx; /* 输入框内部左右边距 */
  box-sizing: border-box;
}

.submit-btn {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  background-color: #007AFF;
  color: #FFFFFF;
  font-size: 32rpx;
  border-radius: 48rpx;
  border: none;
  margin-top: 60rpx;
}

/* Loading弹窗样式 (保持不变) */
.loading-box {
  width: 548.51rpx;
  height: 303rpx;
  background-image: url(/static/loading_background.png);
  background-size: 100% 100%;
  background-position: center;
  border-radius: 10rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top: 4rpx solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 10rpx;
  color: #fff;
  font-size: 32rpx;
}
.text-overlay {
		width: 380rpx;
		height: 89rpx;
		line-height: 43rpx;
		font-family: Source Han Sans,Source Han Sans;
		font-weight: 700;
		font-size: 30rpx;
		color: #FFFFFF;
		text-align: center;
		font-style: normal;
		text-transform: none;
		position: absolute;
		top: 210rpx;
		left: 100rpx;
	  
	}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.device-icon-wrapper { /* 这个是外层容器，负责虚线边框和背景 */
  width: 110rpx;
  height: 110rpx;
  min-width: 110rpx;
  min-height: 110rpx;
  margin-right: 25rpx;
  background-color: #f0f0f0;
  border: 1px dashed #dcdcdc;
  border-radius: 12rpx; /* 外层容器的圆角 */
  display: flex; /* 使内部图片可以居中或撑满 */
  justify-content: center;
  align-items: center;
  overflow: hidden; /* 关键：确保内部图片的圆角效果能正确显示，并裁剪超出部分 */
}

.device-actual-image { /* 这是实际的图片 */
  width: 100%; /* 撑满wrapper，或者设置具体尺寸 */
  height: 100%;/* 撑满wrapper，或者设置具体尺寸 */
  object-fit: cover;
  border-radius: 2rpx; /* 图片本身的圆角 */
}


/* 配网Tab中显示的已选设备信息容器样式 */
.selected-device-display {
  display: flex; /* 使用flex布局，使其子元素（图标包裹器、设备信息块）横向排列 */
  align-items: center; /* 垂直居中对齐图标和设备信息块 */
  padding: 30rpx; /* 内边距，可以和.device-item保持一致 */
  background-color: #fff; /* 白色背景 */
  border-radius: 20rpx; /* 圆角 */
  /* 根据需要，可以添加阴影或边框，使其看起来像一个卡片 */
  /* box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05); */
}

/* 确保复用 .device-info 的样式，但配网中选中的设备信息通常不需要底部分割线 */
.selected-device-display .device-info {
    border-bottom: none; /* 移除底部分割线 */
    padding-bottom: 0; /* 既然没有分割线，也不需要为其底部留空间 */
}

</style>